package com.example.androidtool.notification

import android.app.*
import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Binder
import android.os.Build
import android.os.Process
import android.provider.Settings
import android.widget.RemoteViews
import androidx.core.app.ActivityCompat.startActivityForResult
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import com.example.androidtool.MainActivity
import com.example.androidtool.R

object NotificationUtils {
    var NATIFICATION1 = "natification1"
    var notificationId = 0

    //普通通知
    fun ordinaryNotification(context: Context) {
        val intent = Intent(Intent.ACTION_VIEW, Uri.parse("https://www.baidu.com/"))
        val pendingIntent: PendingIntent = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            PendingIntent.getActivity(context, 1, intent, PendingIntent.FLAG_IMMUTABLE)
        } else {
            PendingIntent.getActivity(context, 1, intent, PendingIntent.FLAG_ONE_SHOT)
        }
        val builder: NotificationCompat.Builder = NotificationCompat.Builder(context, NATIFICATION1)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle("测试")
            .setContentText("收到一条通知消息")
            .setContentIntent(pendingIntent)
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .setAutoCancel(true)
        val build = builder.build()
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            notificationManager.createNotificationChannel(
                NotificationChannel(NATIFICATION1, "测试测试", NotificationManager.IMPORTANCE_HIGH)
            )
        }
        NotificationManagerCompat.from(context).notify(notificationId++, build)
    }

    //展开是的通知
    fun collapseNotification(context: Context) {
        val intent = Intent(Intent.ACTION_VIEW, Uri.parse("https://www.baidu.com/"))
        // 这一行报错
        val pendingIntent: PendingIntent = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            PendingIntent.getActivity(context, 2, intent, PendingIntent.FLAG_IMMUTABLE)
        } else {
            PendingIntent.getActivity(context, 2, intent, PendingIntent.FLAG_ONE_SHOT)
        }

        //折叠布局
        var remoteViews = RemoteViews(context.packageName, R.layout.layout_view_fold)

        val builder: NotificationCompat.Builder = NotificationCompat.Builder(context, NATIFICATION1)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle("折叠标题")
            .setContentText("折叠内容")
            .setContentIntent(pendingIntent)
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .setAutoCancel(true)
            //添加折叠布局
            .setCustomBigContentView(remoteViews)
        val build = builder.build()
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            notificationManager.createNotificationChannel(
                NotificationChannel(NATIFICATION1, "折叠通知", NotificationManager.IMPORTANCE_HIGH)
            )
        }
        NotificationManagerCompat.from(context).notify(notificationId++, build)
    }

    //悬挂通知
    fun hangingNotice(context: Context) {
        val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        val NOTIFICATION_CHANNEL_ID = "my_channel_id_01"
        val intent = Intent(context, MainActivity::class.java)
        var pendingIntent: PendingIntent? = null
        // 适配12.0及以上
        pendingIntent = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_IMMUTABLE)
        } else {
            PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
        }
        // 适配8.0及以上
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(NOTIFICATION_CHANNEL_ID, "Notifications", NotificationManager.IMPORTANCE_HIGH)
            channel.setShowBadge(true)
            notificationManager.createNotificationChannel(channel)
        }

        val mBuilder: NotificationCompat.Builder = NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID)
            .setContentTitle("重要通知")
            .setContentText("重要通知内容")
            .setSmallIcon(R.mipmap.ic_launcher)
            .setLargeIcon(BitmapFactory.decodeResource(context.resources, R.mipmap.ic_launcher))
            .setAutoCancel(true)
            .setNumber(999) // 自定义桌面通知数量
            .setTicker("悬浮")
            .setDefaults(NotificationCompat.DEFAULT_ALL)
            .setPriority(Notification.PRIORITY_HIGH)
            .addAction(R.mipmap.ic_launcher, "去看看", pendingIntent) // 通知上的操作
            .setCategory(NotificationCompat.CATEGORY_MESSAGE) // 通知类别，"勿扰模式"时系统会决定要不要显示你的通知
            .setVisibility(NotificationCompat.VISIBILITY_PRIVATE) // 屏幕可见性，锁屏时，显示icon和标题，内容隐藏
            .setFullScreenIntent(pendingIntent, true)
        notificationManager.notify(1, mBuilder.build())
    }


    fun checkFloatPermission(context: Context): Boolean {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) return true
        return if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            try {
                var cls = Class.forName(context.packageName)
                val declaredField = cls.getDeclaredField("APP_OPS_SERVICE")
                declaredField.isAccessible = true
                var obj: Any? = declaredField[cls] as? String ?: return false
                val str2 = obj as String
                obj = cls.getMethod("getSystemService", String::class.java).invoke(context, str2)
                cls = Class.forName(context.packageName)
                val declaredField2 = cls.getDeclaredField("MODE_ALLOWED")
                declaredField2.isAccessible = true
                val checkOp = cls.getMethod("checkOp", Integer.TYPE, Integer.TYPE, String::class.java)
                val result = checkOp.invoke(obj, 24, Binder.getCallingUid(), context.packageName) as Int
                result == declaredField2.getInt(cls)
            } catch (e: Exception) {
                false
            }
        } else {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                val appOpsMgr = context.getSystemService(Context.APP_OPS_SERVICE) as AppOpsManager ?: return false
                val mode = appOpsMgr.checkOpNoThrow("android:system_alert_window", Process.myUid(), context.packageName)
                mode == AppOpsManager.MODE_ALLOWED || mode == AppOpsManager.MODE_IGNORED
            } else {
                Settings.canDrawOverlays(context)
            }
        }
    }

    fun showPermissionDialog(activity: Activity) {
        val builder: AlertDialog.Builder = AlertDialog.Builder(activity)
        builder.setMessage("Download completion notification requires access\", " +
                "please show it to the permission of \"Show the upper layer " +
                "of other applications -> Allow the upper layer of other applications")
        builder.setPositiveButton("go to manual authorization") { dialog, which ->
            requestSettingCanDrawOverlays(activity)
        }
        builder.setNegativeButton("cancel", null)
        builder.show()
    }


    var MY_PERMISSION_REQUEST_CODE = 10

    //权限打开
    public fun requestSettingCanDrawOverlays(activity: Activity) {
        val sdkInt = Build.VERSION.SDK_INT
        if (sdkInt >= Build.VERSION_CODES.O) { //8.0以上
            val intent = Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION)
            activity.startActivityForResult(intent, MY_PERMISSION_REQUEST_CODE)
        } else if (sdkInt >= Build.VERSION_CODES.M) { //6.0-8.0
            val intent = Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION)
            intent.data = Uri.parse("package:${activity.packageName}")
            activity.startActivityForResult(intent, MY_PERMISSION_REQUEST_CODE)
        } else { //4.4-6.0以下
            //无需处理了
        }
    }
}